import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';
import 'package:flutter_bmflocation/flutter_baidu_location.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_android_option.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_ios_option.dart';
import 'package:flutter_bmfmap/BaiduMap/models/bmf_map_options.dart';
import 'package:flutter_bmfbase/BaiduMap/bmfmap_base.dart';
import 'package:flutter_bmfmap/BaiduMap/bmfmap_map.dart';

var httpClient = new HttpClient();

class BaiduMapPage extends StatefulWidget {
  final callback;

  BaiduMapPage(this.callback, {Key key}) : super(key: key);

  // BaiduMapPage(this.callback);

  @override
  BaiduMapPageState createState() => BaiduMapPageState();
}

class BaiduMapPageState extends State<BaiduMapPage> {
  BMFMapController myMapController;

  /// 我的位置
  BMFUserLocation _userLocation;

  /// 定位点样式
  BMFUserlocationDisplayParam _displayParam;

  //获取的定位位置
  BaiduLocation _baiduLocation;

  StreamSubscription<Map<String, Object>> _locationListener;

  //定位插件
  LocationFlutterPlugin _locationPlugin = new LocationFlutterPlugin();

  //获取的定位结果
  Map<String, Object> _loationResult;

  //屏幕坐标
  BMFPoint screenPointToLock;

  @override
  void initState() {
    super.initState();

    /// 动态申请定位权限
    _locationPlugin.requestPermission();
    _locationListener =
        _locationPlugin.onResultCallback().listen((Map<String, Object> result) {
      setState(() {
        _loationResult = result;

        //发送消息到 百度地图搜索页 用于搜索 1公里的POI地点
        widget.callback(result);
        try {
          _baiduLocation = BaiduLocation.fromMap(result);
          print(_baiduLocation);
        } catch (e) {
          print(e);
        }
      });
    });
    //开始定位
    startLocation();
  }

  @override
  void dispose() {
    super.dispose();
    if (null != _locationListener) {
      _locationListener.cancel();
    }
  }

  /// 启动定位
  void startLocation() {
    if (null != _locationPlugin) {
      _setLocOption();
      _locationPlugin.startLocation();
    }
  }

  /// 停止定位
  void stopLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.stopLocation();
    }
  }

  @override
  void deactivate() {
    super.deactivate();
    startLocation();
  }

  //更新用户位置
  updateLocation() {
    //更新用户位置
    updateUserLocation();
    //定位图层样式
    // updatUserLocationDisplayParam();
    addLocationMarker(_userLocation.location.coordinate.latitude,
        _userLocation.location.coordinate.longitude);
  }

  /// 地图创建完成回调
  void onBMFMapCreated(BMFMapController controller) {
    myMapController = controller;

    /// 地图加载回调
    myMapController?.setMapDidLoadCallback(callback: () {
      // myMapController?.updateMapOptions(BMFMapOptions(scrollEnabled: true));

      //开启定位后跳转到定位位置
      myMapController?.setUserTrackingMode(BMFUserTrackingMode.Follow);
      // 开启地图的定位图层
      myMapController?.showUserLocation(true);
      updateLocation();
    });

    /// 地图区域即将改变时会调用此接口
    /// mapStatus 地图状态信息
    /// regionChangeReason 地图改变原因
    /// 拖拽定位
    myMapController?.setMapRegionDidChangeWithReasonCallback(callback:
        (BMFMapStatus mapStatus, BMFRegionChangeReason regionChangeReason) {
      //改变地图中心点
      myMapController?.setCenterCoordinate(mapStatus.targetGeoPt, true,
          animateDurationMs: 1000);
      //更新用户位置
      addLocationMarker(
          mapStatus.targetGeoPt.latitude, mapStatus.targetGeoPt.longitude);
      //根据拖拽的坐标 获取具体的地理位置
      reverseGeocoding(mapStatus.targetGeoPt.toMap());
    });
  }

  // /   首页 地图选点服务 根据坐标 返回地理数据(地理编码)
  reverseGeocoding(location) async {
    var lantitude = location['latitude'];
    var longitude = location['longitude'];
    Map<String, String> param = {
      'location': "$lantitude,$longitude",
      "ak": "WS9HXr6YEGmdLQWGFHvgrBy5ODT81x1l",
    };
    var uri = new Uri.http('api.map.baidu.com', '/parking/search', param);
    var request = await httpClient.getUrl(uri);
    var response = await request.close();
    if (response.statusCode == 200) {
      print('请求成功');
      var responseBody = await response.transform(utf8.decoder).join();
      Map data = jsonDecode(responseBody);
      setState(() {});
      print('responseBody = $responseBody');
    } else {
      print('请求失败');
    }
  }

  /// 地图路径渲染（骑行路径规划）
  void addColorsPolyline() {
    List<BMFCoordinate> coordinates = List(5);
    coordinates[0] = BMFCoordinate(39.865, 116.304);
    coordinates[1] = BMFCoordinate(39.825, 116.354);
    coordinates[2] = BMFCoordinate(39.855, 116.394);
    coordinates[3] = BMFCoordinate(39.805, 116.454);
    coordinates[4] = BMFCoordinate(39.865, 116.504);

    List<int> indexs = [2, 3, 2, 3];

    List<Color> colors = List(4);
    colors[0] = Colors.blue;
    colors[1] = Colors.orange;
    colors[2] = Colors.red;
    colors[3] = Colors.green;

    BMFPolyline _colorsPolyline = BMFPolyline(
        coordinates: coordinates,
        indexs: indexs,
        colors: colors,
        width: 16,
        lineDashType: BMFLineDashType.LineDashTypeSquare,
        lineCapType: BMFLineCapType.LineCapButt,
        lineJoinType: BMFLineJoinType.LineJoinRound);
    myMapController?.addPolyline(_colorsPolyline);
  }

  /// 更新位置
  void updateUserLocation() {
    BMFCoordinate coordinate =
        BMFCoordinate(_baiduLocation.latitude, _baiduLocation.longitude);
    BMFLocation location = BMFLocation(
        coordinate: coordinate,
        altitude: 0,
        horizontalAccuracy: 5,
        verticalAccuracy: -1.0,
        speed: -1.0,
        course: -1.0);
    BMFUserLocation userLocation = BMFUserLocation(
      location: location,
    );
    _userLocation = userLocation;
    myMapController?.updateLocationData(_userLocation);
  }

  /// 更新定位图层样式
  void updatUserLocationDisplayParam() {
    BMFUserlocationDisplayParam displayParam = BMFUserlocationDisplayParam(
        locationViewOffsetX: 0,
        locationViewOffsetY: 0,
        accuracyCircleFillColor: Colors.red,
        accuracyCircleStrokeColor: Colors.blue,
        isAccuracyCircleShow: true,
        locationViewImage: 'resoures/aj6.png',
        locationViewHierarchy:
            BMFLocationViewHierarchy.LOCATION_VIEW_HIERARCHY_BOTTOM);

    _displayParam = displayParam;
    myMapController?.updateLocationViewWithParam(_displayParam);
  }

  addLocationMarker(latitude, longitude) {
    myMapController?.cleanAllMarkers();

    /// 创建BMFMarker
    var position = BMFCoordinate(latitude, longitude);
    BMFMarker marker = BMFMarker(
        position: position,
        title: '在这里上车',
        subtitle: '在这里上车',
        identifier: 'flutter_marker',
        icon: 'resoures/aj6.png');

    /// 添加Marker
    myMapController?.addMarker(marker);

    /// 构造text
    BMFText bmfText = BMFText(
        text: '在这里上车',
        position: position,
        fontColor: Colors.white,
        fontSize: 40,
        typeFace: BMFTypeFace(
            familyName: BMFFamilyName.sMonospace,
            textStype: BMFTextStyle.BOLD_ITALIC),
        alignY: BMFVerticalAlign.ALIGN_CENTER_VERTICAL,
        alignX: BMFHorizontalAlign.ALIGN_CENTER_HORIZONTAL,
        rotate: 0.0);

    /// 添加text
    myMapController?.addText(bmfText);
  }

  /// 设置android端和ios端定位参数
  void _setLocOption() {
    /// android 端设置定位参数
    BaiduLocationAndroidOption androidOption = new BaiduLocationAndroidOption();
    androidOption.setCoorType("bd09ll"); // 设置返回的位置坐标系类型
    androidOption.setIsNeedAltitude(true); // 设置是否需要返回海拔高度信息
    androidOption.setIsNeedAddres(true); // 设置是否需要返回地址信息
    androidOption.setIsNeedLocationPoiList(true); // 设置是否需要返回周边poi信息
    androidOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    androidOption.setIsNeedLocationDescribe(true); // 设置是否需要返回位置描述
    androidOption.setOpenGps(true); // 设置是否需要使用gps
    androidOption.setLocationMode(LocationMode.Hight_Accuracy); // 设置定位模式
    androidOption.setScanspan(1000); // 设置发起定位请求时间间隔

    Map androidMap = androidOption.getMap();

    /// ios 端设置定位参数
    BaiduLocationIOSOption iosOption = new BaiduLocationIOSOption();
    iosOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    iosOption.setBMKLocationCoordinateType(
        "BMKLocationCoordinateTypeBMK09LL"); // 设置返回的位置坐标系类型
    iosOption.setActivityType("CLActivityTypeAutomotiveNavigation"); // 设置应用位置类型
    iosOption.setLocationTimeout(10); // 设置位置获取超时时间
    iosOption.setDesiredAccuracy("kCLLocationAccuracyBest"); // 设置预期精度参数
    iosOption.setReGeocodeTimeout(10); // 设置获取地址信息超时时间
    iosOption.setDistanceFilter(100); // 设置定位最小更新距离
    iosOption.setAllowsBackgroundLocationUpdates(true); // 是否允许后台定位
    iosOption.setPauseLocUpdateAutomatically(true); //  定位是否会被系统自动暂停

    Map iosMap = iosOption.getMap();

    _locationPlugin.prepareLoc(androidMap, iosMap);
  }

  @override
  Widget build(BuildContext context) {
    //获取屏幕大小
    Size screenSize = MediaQuery.of(context).size;

    //创建地图选项
    BMFMapOptions mapOptions = BMFMapOptions(
        center: BMFCoordinate(39.917215, 116.380341),
        //关闭比列尺
        showMapScaleBar: false,
        zoomLevel: 20,
        mapPadding: BMFEdgeInsets(left: 30, top: 0, right: 30, bottom: 0));

    return Container(
      height: screenSize.height,
      width: screenSize.width,
      child: BMFMapWidget(
        onBMFMapCreated: (controller) {
          onBMFMapCreated(controller);
        },
        mapOptions: mapOptions,
      ),
    );
  }
}
